﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class HYConnectSlop : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			Transaction transaction = null;
			Result result;
			try
			{
				if (commandData == null)
				{
					throw new System.ArgumentNullException("commandData", "is null");
				}
				UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
				Document document = activeUIDocument.Document;
				Selection selection = activeUIDocument.Selection;
				IList<Pipe> list = new List<Pipe>();
				ISelectionFilter selectionFilter = new PipeSelectionFilter();
				HYPipeConnect hypipeConnect = new HYPipeConnect();
				IList<Element> list2 = new List<Element>();
				List<ViewType> viewTypes = YJKRevitTools.ListViewNeed(2);
				if (!YJKRevitTools.ViewCheck(activeUIDocument, viewTypes))
				{
					result = Autodesk.Revit.UI.Result.Cancelled;
				}
				else
				{
					string text = "带坡度连接";
					int num = 0;
					transaction = new Transaction(document, text);
					transaction.Start();
					string text2 = "请框选两条要连接的水管……";
					string text3 = "";
					for (;;)
					{
						SubTransaction subTransaction = new SubTransaction(document);
						IList<Pipe> list3 = new List<Pipe>();
						try
						{
							if (num != 0)
							{
								RevitVersionFuncs.ClearSelection(selection);
								list2.Clear();
								list.Clear();
							}
							num++;
							if (selection.GetElementIds().Any<ElementId>())
							{
								IEnumerator<ElementId> enumerator = selection.GetElementIds().GetEnumerator();
								{
									while (enumerator.MoveNext())
									{
										ElementId elementId = enumerator.Current;
										list3.Add(document.GetElementById(elementId) as Pipe);
									}
									goto IL_112;
								}
							}
							list2 = selection.PickElementsByRectangle(selectionFilter, text2);
							IL_112:
							foreach (Element element in list2)
							{
								if (element is Pipe)
								{
									list3.Add(element as Pipe);
								}
							}
							bool flag = false;
							if (list3.Count == 2)
							{
								XYZ xyz = null;
								string slopConnStyle = hypipeConnect.GetSlopConnStyle(list3, ref xyz);
								if (slopConnStyle == "平行" || slopConnStyle == "直线")
								{
									YJKMessageBox.Show("选择水管投影平面直线\n平行或在一条直线上\n不能连接！");
								}
								else if (this.CheckIsConnector(list3[0]) || this.CheckIsConnector(list3[1]))
								{
									YJKMessageBox.Show("水管已连接，不能连接！");
								}
								else
								{
									XYZ xyz2 = hypipeConnect.OnPipeIntersectionPoint(list3[0], xyz);
									XYZ xyz3 = hypipeConnect.OnPipeIntersectionPoint(list3[1], xyz);
									double num2 = 2.0 * hypipeConnect.GetMaxDiameter(list3);
									subTransaction.Start();
									IList<Connector> listConn = new List<Connector>();
									if (Math.Abs(xyz3.Z - xyz2.Z) > num2)
									{
										listConn = hypipeConnect.CreatSlopPipe(list3);
										Pipe item = hypipeConnect.CreatVertailPipe(list3, xyz);
										IList<Pipe> list4 = new List<Pipe>();
										list4.Add(item);
										list4.Add(hypipeConnect.GetNewPipe(list3[0], xyz2));
										IList<Pipe> list5 = new List<Pipe>();
										list5.Add(item);
										list5.Add(hypipeConnect.GetNewPipe(list3[1], xyz3));
										flag = hypipeConnect.NewBeatchFitting(ref list4);
										hypipeConnect.CreatConnPipe(listConn, list4);
										if (flag)
										{
											flag = hypipeConnect.NewBeatchFitting(ref list5);
											hypipeConnect.CreatConnPipe(listConn, list5);
										}
									}
									else
									{
										int basePipe = this.GetBasePipe(xyz2, xyz3);
										text3 = "";
										if (!(slopConnStyle == "弯头"))
										{
											if (!(slopConnStyle == "三通"))
											{
												if (slopConnStyle == "四通")
												{
													list = hypipeConnect.GetSlopFourPipe(list3, basePipe);
													listConn = hypipeConnect.CreatSlopPipe(list);
													flag = hypipeConnect.NewCrossFitting(ref list, true);
													hypipeConnect.CreatConnPipe(listConn, list);
												}
											}
											else
											{
												list = hypipeConnect.GetSlopTeePipe(list3);
												listConn = hypipeConnect.CreatSlopPipe(list);
												flag = hypipeConnect.NewTeeFitting(ref list, true);
												hypipeConnect.CreatConnPipe(listConn, list);
											}
										}
										else
										{
											list = hypipeConnect.GetSlopElbowPipe(list3, basePipe);
											listConn = hypipeConnect.CreatSlopPipe(list);
											flag = (hypipeConnect.NewElbowFitting(list, this.GetPipeMiddlePoint(list), ref text3) != null);
											hypipeConnect.CreatConnPipe(listConn, list);
										}
									}
									if (!flag)
									{
										if (string.IsNullOrEmpty(text3))
										{
											text3 = "连接失败";
										}
										MessageBox.Show(text3, "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
										subTransaction.RollBack();
									}
									else
									{
										document.Regenerate();
										subTransaction.Commit();
									}
								}
							}
						}
						catch (Autodesk.Revit.Exceptions.OperationCanceledException)
						{
							result = Autodesk.Revit.UI.Result.Succeeded;
							break;
						}
						catch (Exception ex)
						{
							MessageBox.Show(ex.Message, "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
							subTransaction.RollBack();
						}
						finally
						{
							if (subTransaction != null)
							{
								TransactionStatus status = subTransaction.GetStatus();
								if ((int)status == 1)
								{
									subTransaction.Commit();
								}
								else if ((int)status == 5)
								{
									subTransaction.RollBack();
								}
							}
						}
					}
				}
			}
			catch (Autodesk.Revit.Exceptions.OperationCanceledException)
			{
				result = Autodesk.Revit.UI.Result.Succeeded;
			}
			catch (Exception ex2)
			{
				message = ex2.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			finally
			{
				if (transaction != null)
				{
					TransactionStatus status2 = transaction.GetStatus();
					if ((int)status2 == 1)
					{
						transaction.Commit();
					}
					else if ((int)status2 == 5)
					{
						transaction.RollBack();
					}
				}
			}
			return result;
		}

		private int GetBasePipe(XYZ pntOne, XYZ pntTwo)
		{
			int result;
			if (pntOne.Z < pntTwo.Z)
			{
				result = 0;
			}
			else
			{
				result = 1;
			}
			return result;
		}

		private IList<XYZ> GetPipeMiddlePoint(IList<Pipe> listPipe)
		{
			IList<XYZ> list = new List<XYZ>();
			foreach (Pipe piping in listPipe)
			{
				YJKPiping<Pipe> hypiping = new YJKPiping<Pipe>(piping);
				list.Add(hypiping.StartConnector.Origin.Add(hypiping.EndConnector.Origin) / 2.0);
			}
			return list;
		}

		private bool CheckIsConnector(Pipe pipe)
		{
			bool result = false;
			int size = pipe.ConnectorManager.Connectors.Size;
			int num = 0;
			IEnumerator enumerator = pipe.ConnectorManager.Connectors.GetEnumerator();
			{
				while (enumerator.MoveNext())
				{
					if (((Connector)enumerator.Current).IsConnected)
					{
						num++;
					}
				}
			}
			if (num == size)
			{
				result = true;
			}
			return result;
		}
	}
}
